package com.streetlight.lampcursor.ui.settings

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.streetlight.lampcursor.model.SettingsData
import com.streetlight.lampcursor.repository.StreetLightRepository
import kotlinx.coroutines.launch

class SettingsViewModel : ViewModel() {

    private val repository = StreetLightRepository()

    private val _settings = MutableLiveData<SettingsData>()
    val settings: LiveData<SettingsData> = _settings

    private val _saveResult = MutableLiveData<SaveResult>()
    val saveResult: LiveData<SaveResult> = _saveResult

    fun loadSettings() {
        viewModelScope.launch {
            try {
                val settingsData = repository.getSettings()
                _settings.value = settingsData
            } catch (e: Exception) {
                // 处理错误
            }
        }
    }

    fun saveSettings(settings: SettingsData) {
        viewModelScope.launch {
            try {
                val result = repository.updateSettings(settings)
                if (result) {
                    _saveResult.value = SaveResult.Success
                } else {
                    _saveResult.value = SaveResult.Error("保存设置失败")
                }
            } catch (e: Exception) {
                _saveResult.value = SaveResult.Error("网络错误: ${e.message}")
            }
        }
    }

    sealed class SaveResult {
        object Success : SaveResult()
        data class Error(val message: String) : SaveResult()
    }
} 